package com.control.qct.businesssteward.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.control.qct.businesssteward.R;
import com.control.qct.businesssteward.adapter.CheckDetailAdapter;
import com.control.qct.businesssteward.base.BaseBean;
import com.control.qct.businesssteward.base.BaseFragment;
import com.control.qct.businesssteward.httputils.HttpUtils;
import com.control.qct.businesssteward.model.CheckBatchNoAndCheckersModel;
import com.control.qct.businesssteward.model.CheckDetailModel;
import com.control.qct.businesssteward.utils.CustomCodeUtils;
import com.control.qct.businesssteward.utils.PopUtils;
import com.control.qct.businesssteward.costom.NumberPictureDivider;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 盘点明细
 * Created by Administrator on 2017/12/11 0011.
 */

public class CheckDetailFragment extends BaseFragment implements CheckOperateFragment.ICheckOperateCallbackListener,
        BaseQuickAdapter.RequestLoadMoreListener, CustomCodeUtils.ICallbackListener {
    @BindView(R.id.et_barcode)
    EditText mEtBarcode;//输入条形码
    @BindView(R.id.iv_sure)
    ImageView mIvSure;
    @BindView(R.id.iv_scan)
    ImageView mIvScan;
    @BindView(R.id.tv_batch)
    TextView mTvBatch;//批次
    @BindView(R.id.tv_check_member)
    TextView mTvCheckMember;//盘点员
    @BindView(R.id.rv_check_goods)
    RecyclerView mRvCheckGoods;

    private List<CheckBatchNoAndCheckersModel.CheckersBean> mCheckersBeanList;
    private List<String> mBatchNos;
    private List<CheckDetailModel.DatasBean> mCheckDetailModels = new ArrayList<>();
    private CheckDetailAdapter mCheckDetailAdapter;
    private int[] mBatchNosSelectId = new int[2];//批次选择id
    private int[] mCheckersSelectId = new int[2];//盘点选择id
    private List<String> mCheckersList = new ArrayList<>();
    private int mPageNum = 1;
    private String mCheckBatch = "";
    private String mBarcode = "";
    private String mCheckUid = "";
    private boolean isSelectBatchNo;

    @Override
    protected View initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        return inflater.inflate(R.layout.fragment_check_detail, container, false);
    }

    @Override
    protected void initView(View view) {
        activity.setLeftIcon(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                activity.finish();
            }
        });
        activity.setTitle("盘点");
        getCheckBatchNoAndCheckers();
        setEtHintSize();
        mRvCheckGoods.setLayoutManager(new LinearLayoutManager(activity));
        mCheckDetailAdapter = new CheckDetailAdapter(mCheckDetailModels);
        mRvCheckGoods.setAdapter(mCheckDetailAdapter);
        mCheckDetailAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                activity.replaceFragment(R.id.fl_content, new CheckOperateFragment(mCheckDetailModels.get(position),
                        mBatchNos.get(mBatchNosSelectId[1]), CheckDetailFragment.this), true);
            }
        });
    }

    /**
     * 设置条形码hint文字大小
     */
    private void setEtHintSize() {
//        新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString(getString(R.string.barcode_hint));
//        新建一个属性对象,设置文字的大小,true为dip，附加属性到文本
        ss.setSpan(new AbsoluteSizeSpan(13, true), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        设置hint
        mEtBarcode.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
    }

    @OnClick({R.id.iv_sure, R.id.iv_scan, R.id.tv_batch, R.id.tv_check_member})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_sure://确认
                mBarcode = mEtBarcode.getText().toString();
                if (TextUtils.isEmpty(mBarcode)) {
                    showShortToast("请输入条码号！");
                    return;
                }
                if (TextUtils.isEmpty(mCheckBatch)) {
                    showShortToast("请先选择批次号！");
                    return;
                }
                mPageNum = 1;
                mEtBarcode.setText("");
                mCheckDetailModels.clear();
                getTakeStockList(true);
                break;
            case R.id.iv_scan://扫描
                CustomCodeUtils.getInstance(activity).startToCaptureActivity(this);
                break;
            case R.id.tv_batch://批次
                if (mBatchNos == null) {
                    showShortToast("请在我的模块中选择所属门店！");
                    return;
                }
                if (mBatchNos.size() == 0) {
                    showShortToast("该门店没有商品批次，请选择其他门店！");
                    return;
                }
                setCheckPopBottom(1, mBatchNos);
                break;
            case R.id.tv_check_member://盘点员
                if (mCheckersBeanList == null) {
                    showShortToast("请在我的模块中选择所属门店！");
                    return;
                }
                if (mCheckersBeanList.size() == 0) {
                    showShortToast("该门店没有盘点员，请选择其他门店！");
                    return;
                }
                if (!isSelectBatchNo) {
                    showShortToast("请先选择批次！");
                    return;
                }
                setCheckPopBottom(2, mCheckersList);
                break;
        }
    }

    /**
     * 根据门店获取相关批次和盘点员列表
     */
    private void getCheckBatchNoAndCheckers() {
        mNetProtocol.getCheckBatchNoAndCheckers(activity, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                CheckBatchNoAndCheckersModel checkBatchNoAndCheckersModel = (CheckBatchNoAndCheckersModel) baseBean
                        .getData();
                mBatchNos = checkBatchNoAndCheckersModel.getBatchnos();
                mCheckersBeanList = checkBatchNoAndCheckersModel.getCheckers();
                for (int i = 0; i < mCheckersBeanList.size(); i++) {
                    mCheckersList.add(mCheckersBeanList.get(i).getName());
                }
            }

            @Override
            public void onFail(BaseBean baseBean) {
//                showShortToast(baseBean.getMessage());
            }
        });
    }

    /**
     * 获取盘点列表明细
     */
    private void getTakeStockList(boolean isShow) {
        Map<String, String> params = new HashMap<>();
        params.put("checkBatch", mCheckBatch);
        params.put("barcode", mBarcode);
        params.put("checkUid", mCheckUid);
        params.put("page", mPageNum + "");
        params.put("rows", "10");

        mNetProtocol.getTakeStockList(activity, params, isShow, new HttpUtils.IHttpResult() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                CheckDetailModel checkDetailModel = (CheckDetailModel) baseBean.getData();
                mCheckDetailModels.addAll(checkDetailModel.getDatas());
                if (mCheckDetailAdapter != null) {
                    if (mCheckDetailModels.size() == 0) {
                        mCheckDetailAdapter.setEmptyView(R.layout.nothing_search_view, mRvCheckGoods);
                    }
                    if (checkDetailModel.getDatas().size() > 0) {
                        mCheckDetailAdapter.setOnLoadMoreListener(CheckDetailFragment.this, mRvCheckGoods);
                        mCheckDetailAdapter.loadMoreComplete();//加载完成
                    } else {
                        mCheckDetailAdapter.loadMoreEnd();//加载结束 没有更多数据,不再去请求网络
                    }
                    mCheckDetailAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFail(BaseBean baseBean) {
                showShortToast(baseBean.getMessage());
            }
        });
    }


    /**
     * 设置底部弹窗
     */
    private void setCheckPopBottom(final int id, final List<String> content) {
        View view = View.inflate(activity, R.layout.pop_check_detail, null);
        final PopupWindow pop = PopUtils.getInstance().getBottomPop(activity, view);
        TextView tvSure = view.findViewById(R.id.tv_sure);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        TextView tvEmpty = view.findViewById(R.id.tv_empty);
        NumberPicker npCheckType = view.findViewById(R.id.np_check_type);
        npCheckType.setDisplayedValues(content.toArray(new String[content.size()]));
        //设置不可编辑
        npCheckType.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        NumberPictureDivider.getInstance().setNumberPickerDividerColor(npCheckType, android.R.color.transparent);
        npCheckType.setMinValue(0);
        npCheckType.setMaxValue(content.size() - 1);
        npCheckType.setValue(id == 1 ? mBatchNosSelectId[1] : mCheckersSelectId[1]);
        npCheckType.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int oldId, int newId) {
                if (id == 1) {
                    mBatchNosSelectId[0] = newId;
                } else {
                    mCheckersSelectId[0] = newId;
                }
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop.dismiss();
            }
        });
        if (id == 1) {
            tvEmpty.setText("批次");
        } else {
            tvEmpty.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mCheckUid = "";
                    mTvCheckMember.setText("盘点员");
                    getTakeStockList(true);
                    pop.dismiss();
                }
            });
        }
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBarcode = "";
                mPageNum = 1;
                mCheckDetailModels.clear();
                if (id == 1) {
                    mBatchNosSelectId[1] = mBatchNosSelectId[0];
                    mCheckBatch = content.get(mBatchNosSelectId[1]);
                    isSelectBatchNo = true;
                    mTvBatch.setText(mCheckBatch + "");
                    getTakeStockList(true);
                } else {
                    mCheckersSelectId[1] = mCheckersSelectId[0];
                    mCheckUid = mCheckersBeanList.get(mCheckersSelectId[1]).getUid();
                    mTvCheckMember.setText(mCheckersBeanList.get(mCheckersSelectId[1]).getName() + "");
                    getTakeStockList(true);
                }
                pop.dismiss();
            }
        });
        //设置PopupWindow显示位置
        pop.showAtLocation(activity.findViewById(R.id.fl_content), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CustomCodeUtils.getInstance(activity).onCallBackListener(requestCode, data, this);
    }

    @Override
    public void result(String mBatchNo) {
        mCheckBatch = mBatchNo;
        mCheckDetailModels.clear();
        getTakeStockList(false);
    }

    @Override
    public void onLoadMoreRequested() {
        mPageNum++;
        getTakeStockList(false);
    }

    @Override
    public void onCallbackListener(String result) {
        mBarcode = result;
        mPageNum = 1;
        mCheckDetailModels.clear();
        getTakeStockList(true);
    }
}

